package com.wwt.blog.imp;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wwt.blog.mapper.LoginMapper;
import com.wwt.blog.pojo.SysUser;
import com.wwt.blog.service.LoginService;
import com.wwt.blog.utils.JWTUtils;
import com.wwt.blog.vo.ErrorCode;
import com.wwt.blog.vo.Result;
import com.wwt.blog.vo.param.LoginParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    LoginMapper loginMapper;
    //加密盐
    private static final String slat="mszlu!@#";
    //注入redis模板
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
        //根据账号密码查找用户
        public Result findUser(LoginParam loginParam) {
            String account=loginParam.getAccount();
            String password=loginParam.getPassword();
            //判断参数是否正常
            if(StringUtils.isEmpty(account)||StringUtils.isEmpty(password)){
                return Result.result_fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
            }

            //md5加密
        String pwd = DigestUtils.md5Hex(password + slat);
        LambdaQueryWrapper<SysUser> wrapper=new LambdaQueryWrapper();
            //查询条件
            wrapper.eq(SysUser::getAccount,account)
                    .eq(SysUser::getPassword,pwd)
                    .last("limit 1")
                    .select(SysUser::getAccount,SysUser::getAdmin,SysUser::getNickname,SysUser::getId,SysUser::getAvatar);
            SysUser user = loginMapper.selectOne(wrapper);
            if(user==null)
                return Result.result_fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(),ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
            //生成token
            String token = JWTUtils.createToken(user.getId());
            //存入redis
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(user),1, TimeUnit.DAYS);
        return Result.result_success(token);
        }

    @Override
    public Result logOut(String token) {
        if(StringUtils.isEmpty(token))
           return Result.result_fail(ErrorCode.TOKEN_AUTH_FAILED.getCode(),ErrorCode.TOKEN_AUTH_FAILED.getMsg());
        redisTemplate.delete("TOKEN_"+token);
        return Result.result_success("删除token成功！");
    }
}
